package com.cuckoo.cuckoo_app2.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.icu.text.SimpleDateFormat;
import android.media.AudioAttributes;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import com.cuckoo.cuckoo_app2.MyApplication;
import com.cuckoo.cuckoo_app2.R;
import com.cuckoo.cuckoo_app2.apiAsync.BaseCallbac;
import com.cuckoo.cuckoo_app2.apiAsync.Imp.PlatformApiImp;
import com.cuckoo.cuckoo_app2.apiAsync.PlatformApi;
import com.cuckoo.cuckoo_app2.business.Imp.PlatformBusinessImp;
import com.cuckoo.cuckoo_app2.business.Imp.UserBusinessImp;
import com.cuckoo.cuckoo_app2.business.PlatformBusiness;
import com.cuckoo.cuckoo_app2.business.UserBusiness;
import com.cuckoo.cuckoo_app2.dao.UserPlatformDao;
import com.cuckoo.cuckoo_app2.dao.VipCard;
import com.cuckoo.cuckoo_app2.enums.NotificationChannelsEnum;
import com.cuckoo.cuckoo_app2.ui.MainActivity;
import com.cuckoo.cuckoo_app2.utils.DialogUtils;
import com.cuckoo.cuckoo_app2.utils.MessageCodeUtils;
import com.cuckoo.cuckoo_app2.utils.NotificationUtils;
import com.cuckoo.cuckoo_app2.utils.RouteUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


public class MyBackgroundService extends Service {

    private String appName;
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    // 线程通讯器
    private final Messenger mMessenger = new Messenger(new IncomingHandler());
    private MessageService messageService;
    private Context context;
    private SchedulerService schedulerService;
    private PlatformBusiness platformBusiness = new PlatformBusinessImp();
    private PlatformApi platformApi = new PlatformApiImp();

    private static final String NOTIFICATION_TITLE = "布谷鸟后台服务";
    private static final String NOTIFICATION_TEXT = "布谷鸟后台服务：请勿关闭应用";


    String CHANNEL_ID = "task"; // 定义渠道ID

    /**
     * 当服务被创建时调用
     *
     * @return
     */
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("TEST", "MyBackgroundService.onCreate()");
        Resources resources = getResources();
        this.context = this;
        this.appName = resources.getString(R.string.app_name);
        this.messageService = new MessageService(this);
        this.schedulerService = new SchedulerService(this);
        this.initGlobal();
    }

    /**
     * 当服务启动时调用（每次启动服务时都会调用）
     *
     * @return
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("TEST", "MyBackgroundService.onStartCommand()");
        // 创建并设置Notification
        Notification notification = createNotification();
        // 将服务设置为前台服务
        startForeground(NotificationChannelsEnum.NOTIFICATION_CHANNEL_ID, notification);

        // 在这里编写你的服务逻辑，如启动线程来执行后台任务
        this.initServer();
        this.initData();
        // 返回START_STICKY使得服务在被杀死后能够自动重启
        return START_STICKY;
    }

    /**
     * 当服务被绑定时调用（如果你的服务支持绑定）
     *
     * @return
     */
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.d("TEST", "MyBackgroundService.onBind()");
        // 返回一个IBinder，用于客户端与服务进行通信（如果不需要绑定，则返回null）
        return mMessenger.getBinder();
    }

    /**
     * 当服务被销毁时调用
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("TEST", "MyBackgroundService.onDestroy()");
        // 清理代码，如停止线程等
    }

    /**
     * 内部类 消息处理
     */
    class IncomingHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            MessageCodeUtils codeUtils = MessageCodeUtils.fromCode(msg.what);
            switch (codeUtils) {
                case TASK_SERVEICE: // 接单任务
                    messageService.taskServeice(msg.obj);
                    return;
                case UPDATE_BACKGROUND_DATA: // 更新后台版本数据
                    initData();
                    checkVip();
                    syncPlatformList();
                    return;
                case DELETE_LOGIN_EXPIRE: // 登录过期
                    loginOut();
                    return;
            }
            super.handleMessage(msg);
        }
    }


    /**
     * 定时任务
     */
    public void timedTasks() {
        // 初始启动定时器
        ScheduledExecutorService scheduler = MyApplication.getInstances().getScheduler();
        if (scheduler instanceof ScheduledThreadPoolExecutor) {
            ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = (ScheduledThreadPoolExecutor) scheduler;
            int poolSize = scheduledThreadPoolExecutor.getPoolSize();
            Log.i("TEST", "线程数量：" + poolSize);
        }
        Runnable task = new Runnable() {
            public void run() {
                String message = "当前时间为：" + dateFormat.format(new Date());
                Log.i("TEST", "scheduleWithFixedDelay 定时任务 " + message);
                // 启动请求平台列表
                schedulerService.monitorTaskTherad();
                // 安排自己再次执行，实现循环
                scheduler.schedule(this, 10, TimeUnit.SECONDS);
            }
        };
        // 首次安排任务
        scheduler.schedule(task, 10, TimeUnit.SECONDS); // 立即执行，然后每10秒执行一次

        // 初始延迟3秒，之后每1分站执行一次
        Runnable task2 = new Runnable() {
            public void run() {
                String message = "当前时间为：" + dateFormat.format(new Date());
                Log.i("TEST", "定时任务 vip-版本" + message);
                checkVip();

                // 安排自己再次执行，实现循环
                scheduler.schedule(this, 60, TimeUnit.SECONDS);
            }
        };
        scheduler.schedule(task2, 5, TimeUnit.SECONDS); // 立即执行，然后每10秒执行一次
    }

    /**
     * 初始化服务
     */
    public void initServer() {
        this.timedTasks();
    }

    private void initGlobal() {
        MyApplication.getInstances().setmMessenger(mMessenger);
    }

    /**
     * 初始化数据
     */
    public void initData() {
        Log.i("TEST", "后台初始化数据");

        // 更新个人数据
        UserBusiness userBusiness = new UserBusinessImp();
        userBusiness.updateUserInfoContext();

        // 更新所有平台数据列表
        NetUpdateService netUpdateService = new NetUpdateService();
        netUpdateService.updateBackgroundData();
    }

    /**
     * 检测Vip接口
     */
    public void checkVip() {
        // vip检测
        UserBusiness userBusiness = new UserBusinessImp();
        userBusiness.getVipInfo();

        // 更新版本信息
        NetUpdateService netUpdateService = new NetUpdateService();
        netUpdateService.getVersion();
    }

    /**
     * 退出登录
     */
    public void loginOut() {
        // 清除登录信息
        UserBusiness userBusiness = new UserBusinessImp();
        userBusiness.deleteAll();

        // 跳转登录页面
        RouteUtils.toLoginActivity(context);
    }

    //定义前台服务
    private Notification createNotification() {
        // 创建一个Intent，指向你想要跳转的Activity
        Intent intent = new Intent(context, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        // 创建一个PendingIntent，当通知被点击时执行这个Intent
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE);

        // 创建一个NotificationCompat.Builder对象，并设置通知的标题、内容、图标等
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
                .setSmallIcon(R.drawable.logo_no)
                .setContentTitle(NOTIFICATION_TITLE)
                .setContentText(NOTIFICATION_TEXT)
                .setContentIntent(pendingIntent);

        // 对于Android Oreo（8.0）及以上版本，创建通知渠道
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    NOTIFICATION_TITLE,
                    NotificationManager.IMPORTANCE_LOW
            );
            notificationManager.createNotificationChannel(channel);
        }

        // 返回构建好的Notification对象
        return builder.build();
    }

    /**
     * 云同步我的平台列表
     */
    public void syncPlatformList() {
        platformApi.PlatformListAsync(new BaseCallbac<JsonObject>() {
            @Override
            public void onSuccess(JsonObject data) {
                if (!data.get("success").getAsBoolean()) {
                    DialogUtils.showToast(context, data.get("message").getAsString());
                    return;
                }
                JsonArray result = data.get("result").getAsJsonArray();
                Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
                List<UserPlatformDao> list = new ArrayList<>();
                for (int i = 0; i < result.size(); i++) {
                    list.add(gson.fromJson(result.get(i), UserPlatformDao.class));
                }
                platformBusiness.syncList(list);
            }

            @Override
            public void onFailure(String errorMessage) {

            }
        });

    }
}
